package com.agent.commons.utils;

import com.agent.commons.exception.BaseException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.channels.FileChannel;
import java.util.UUID;

import static com.agent.commons.errorcode.ServiceErrorCodeConstants.FILE_UPLOAD_DEFEAT;

/**
 * IO流工具类
 */
@Slf4j
public class IOUtil {
    private static final String rootUrl="D:\\JavaProject\\agent\\file\\";

    /**
     * 保存图片到本地
     * @Input fileStream
     */
    public static String saveImage(InputStream fileStream,String fileName) {
        String file=rootUrl+ UUID.randomUUID()+"_"+fileName;
        try(FileOutputStream out=new FileOutputStream(file)) {
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = fileStream.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
            return file;
        }catch (Exception e){
            log.error("保存图片失败",e);
            throw new BaseException(FILE_UPLOAD_DEFEAT);
        }
    }

    /**
     * 保存图片到本地
     * @Input file
     */
    public static String saveImage(MultipartFile file){
        try {
            return saveImage(file.getInputStream(), file.getOriginalFilename());
        }catch (Exception e){
            log.error("保存图片失败",e);
            throw new BaseException(FILE_UPLOAD_DEFEAT);
        }
    }


    /**
     * 删除本地保存的图片
     */
    public static boolean deleteImage(String fileName){
        File file = new File(fileName);
        if (file.exists()) {
            return file.delete();
        }
        return false;
    }


    /**
     * 获取输入流大小
     * @param fileStream
     * @return
     * @throws IOException
     */
    public static Long getInputSize(InputStream fileStream) throws IOException {
        // 如果是文件流则直接获取大小
        if (fileStream instanceof FileInputStream) {
            FileChannel channel = ((FileInputStream) fileStream).getChannel();
            return channel.size();
        }

        // 判断是否为可重复读取的缓冲流方案
        if (!fileStream.markSupported()) {
            //否，强转成缓冲流
            fileStream = new BufferedInputStream(fileStream);
        }
        fileStream.mark(Integer.MAX_VALUE);
        long size = 0;
        //一次读取最大的字节数
        byte[] buffer = new byte[8192];
        int bytesRead;
        //分块读取文件大小
        while ((bytesRead = fileStream.read(buffer)) != -1) {
            size += bytesRead;
        }
        // 重置流位置
        fileStream.reset();
        return size;
    }
}
